package app.controllers.mobileweb;

import app.Const;
import app.dtos.MemberSmsCode;
import app.dtos.status.MemberStatus;
import app.interceptors.MobileWxMemberInterceptor;
import app.kits.SmsWsKit;
import app.models.member.Member;
import app.models.sys.Sn;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.kit.common.RandomStringKit;
import com.github.sog.kit.date.DateProvider;
import com.github.sog.libs.AppFunc;
import com.github.sog.validator.ValidatorKit;
import com.google.common.base.Strings;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.ehcache.CacheKit;
import org.apache.commons.lang3.StringUtils;

import java.sql.SQLException;

/**
 * <p>
 * 会员中心
 * </p>
 *
 * @author liuhui
 * @version 1.0 2014-04-22 10:25
 * @since JDK 1.6
 */
@Before(MobileWxMemberInterceptor.class)
public class MemberController extends BasicController {

    public void index() {
        long mid = getParaToLong(Const.MEMBER_PARAM, 0l);
        Member member = Member.dao.findById(mid);
        if (null != member) {
            setAttr(Const.MEMBER_ATTR, member);
        } else {
            return;
        }
        render("index.ftl");
    }

    public void phone() {
    }

    @Before(POST.class)
    public void code() {
        String phone = getPara("phone");
        if (Strings.isNullOrEmpty(phone)) {
            renderJson(AjaxMessage.nodata());
        } else {
            final boolean mobile = ValidatorKit.isMobile(phone);
            if (mobile) {
                MemberSmsCode memberSmsCode = CacheKit.get(Const.CACHE_SMSCODE_MEMBER, phone);
                if (memberSmsCode != null) {
                    renderSuccess();
                    return;
                }

                final String catcha = RandomStringKit.randomNumeric(6);
                memberSmsCode = new MemberSmsCode(phone, catcha, DateProvider.DEFAULT.getCurrentTimeInMillis());
                CacheKit.put(Const.CACHE_SMSCODE_MEMBER, phone, memberSmsCode);
                // todo 30 with settings
                SmsWsKit.membreApplySend(phone, catcha, 30);
                renderSuccess();
            } else {
                renderJson(AjaxMessage.failure("请输入正确的手机号码!"));
            }
        }
    }

    @Before(POST.class)
    public void check() {
        long memberId = getParaToLong(0, 0l);
        String phone = getPara("phone");
        String code = getPara("code");
        if (Strings.isNullOrEmpty(phone) || Strings.isNullOrEmpty(code)) {
            renderJson(AjaxMessage.failure("请输入手机号码或者验证码!"));
        } else {
            final boolean mobile = ValidatorKit.isMobile(phone);
            if (mobile) {
                final MemberSmsCode memberSmsCode = CacheKit.get(Const.CACHE_SMSCODE_MEMBER, phone);
                long now = DateProvider.DEFAULT.getCurrentTimeInMillis();

                if (StringUtils.equals(memberSmsCode.getCode(), code)) {
                    if ((now - memberSmsCode.getTime()) > 60000) {
                        CacheKit.remove(Const.CACHE_SMSCODE_MEMBER, phone);
                        renderJson(AjaxMessage.failure("验证码无效！"));
                    } else {
                        Member member = Member.dao.findById(memberId);
                        member.set("phone", phone);
                        member.set("name", getPara("name"));
                        member.update();
                        renderJson(AjaxMessage.ok());
                    }
                } else {
                    renderJson(AjaxMessage.failure("验证码无效！"));
                }
            } else {
                renderJson(AjaxMessage.failure("请输入正确的手机号码!"));
            }
        }
    }

    public void complete() {
        Member member = Member.dao.findById(getParaToLong(Const.MEMBER_PARAM));
        setAttr(Const.MEMBER_ATTR, member);
    }

    @Before(POST.class)
    public void save() {
        Member member = getModel(Member.class);
        member.set("card_no", Sn.dao.member());
        member.set("temp", false);
        // register ok.
        member.set("register", true);
        member.set(Const.COLUMN_STATUS, MemberStatus.REGISTERED);
        member.update();
        renderSuccess();
    }

    /**
     * 会员须知
     */
    public void notice() { }

    /**
     * 兑换页面
     */
    public void exchange() { }

    /**
     * 卡号绑定页面
     */
    public void bindCard() {
        long mid = getParaToLong(Const.MEMBER_PARAM, 0l);
        Member member = Member.dao.findById(mid);
        setAttr("member", member);
        render("bindcard.ftl");
    }

    /**
     * 绑定会员卡
     */
    public void bindCardExcute() {
        long mid = getParaToLong(Const.MEMBER_PARAM, 0l);

        if (mid > 0) {
            String cardNo = getPara("carno");
            String mobno = getPara("phoneno");
            //CRM系统已经导入的数据
            final Member oldMem = Member.dao.findByCarIdAndMno(cardNo, mobno);
            final Member member = Member.dao.findById(mid);

            if (null != oldMem && null != member) {
                if (oldMem.getLong(AppFunc.TABLE_PK_COLUMN).equals(member.getLong(AppFunc.TABLE_PK_COLUMN))) {
                    renderError("你的卡号已经成功绑定");
                } else {
                    oldMem.remove("wx_no");
                    oldMem.remove("wx_nickname");
                    member.setAttrs(oldMem);
                    member.set("id", mid);
                    member.set("temp", false);
                    member.set(Const.COLUMN_STATUS, MemberStatus.OFFICIAL);
                    member.set("update_time", DateProvider.DEFAULT.getCurrentDate());

                    boolean tx = Db.tx(new IAtom() {
                        @Override
                        public boolean run() throws SQLException {
                            boolean update = member.update();
                            boolean delete = oldMem.delete();
                            return update && delete;
                        }
                    });
                    if (tx) {
                        renderSuccess();
                    } else {
                        renderError("绑定失败，请重新尝试");
                    }
                }
            } else {
                renderError("卡号或手机号不正确，请重新绑定");
            }
        }
    }
}
